/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.utils.Query;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.form.SysLoginForm;
import io.renren.modules.sys.service.SysCaptchaService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * 登录相关
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
public class SysLoginController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserTokenService sysUserTokenService;
	@Autowired
	private SysCaptchaService sysCaptchaService;
	private  String auth_code;

	//前端跳转地址

	private String URL="";

   private String Private_key="";

	private String Public_key="";
	/**
	 * 验证码
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletResponse response, String uuid)throws IOException {
		response.setHeader("Cache-Control", "no-store, no-cache");
		response.setContentType("image/jpeg");

		//获取图片验证码
		BufferedImage image = sysCaptchaService.getCaptcha(uuid);

		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}

	/**
	 * 登录
	 */
	@PostMapping("/sys/login")
	public Map<String, Object> login(@RequestBody SysLoginForm form,HttpServletRequest request)throws IOException {
		String userId = null;
		try {
			userId = (String) request.getServletContext().getAttribute("userId");
		if (!userId.equals("")||userId!=null) {
			request.getServletContext().removeAttribute("userId");
			QueryWrapper<SysUserEntity> wrapper=new QueryWrapper<>();
			wrapper.eq("user_ids",userId);
			List<SysUserEntity> list = sysUserService.list(wrapper);
			if(list.size()>0){
				SysUserEntity userEntity = list.get(0);
				if(userEntity!=null){
					//账号锁定
					if(userEntity.getStatus() == 0){
						return R.error("账号已被锁定,请联系管理员");
					}

					//生成token，并保存到数据库
					R r = sysUserTokenService.createToken(userEntity.getUserId());
				return  r;
				}
			}else{
				return R.error(400,"没有授权用户请联系管理员添加");
			}
		}
		} catch (Exception e) {
		}
		boolean captcha = sysCaptchaService.validate(form.getUuid(), form.getCaptcha());
		if(!captcha){
			return R.error("验证码不正确");
		}

		//用户信息
		SysUserEntity user = sysUserService.queryByUserName(form.getUsername());

		//账号不存在、密码错误
		if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		//账号锁定
		if(user.getStatus() == 0){
			return R.error("账号已被锁定,请联系管理员");
		}

		//生成token，并保存到数据库
		R r = sysUserTokenService.createToken(user.getUserId());
		return r;
	}
	/**
	 *
	 * auth_code
	 */
	@RequestMapping("/sys/auth_code")
	public void auth_code(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		 //获取支付宝的auth_code
		String  auth_code=request.getParameter("auth_code");
          AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2017112600190731", Private_key, "json", "gbk", Public_key, "RSA2");
		AlipaySystemOauthTokenRequest request1 = new AlipaySystemOauthTokenRequest();
		request1.setCode(auth_code);
		request1.setGrantType("authorization_code");
		try {
			//获取支付宝的个人userid
			AlipaySystemOauthTokenResponse execute = alipayClient.execute(request1);
			System.out.println(execute.getUserId()+"******");
			request.getServletContext().setAttribute("userId",execute.getUserId());
		} catch (AlipayApiException e) {

		}
		response.sendRedirect(URL);
	}

	/**
	 * 退出
	 */
	@PostMapping("/sys/logout")
	public R logout(HttpServletRequest request) {
		sysUserTokenService.logout(getUserId());
		request.getServletContext().setAttribute("userId",null);
		return R.ok();
	}
	
}
